<template>
  <div class="container">
    <div class="header">
      <h2>📑 分账协议管理</h2>
      <div class="actions">
        <button class="btn primary" @click="openAddModal">新增分账协议</button>
      </div>
    </div>

    <div class="filters">
      <div class="filter-row">
        <label class="filter-label">关键词</label>
        <input class="input flex-1" v-model="filters.key" placeholder="按协议名称搜索" @input="onKeyChange" />

        <label class="filter-label">商户ID</label>
        <input class="input" v-model="filters.merchantId" placeholder="可选" @change="reload" />

        <label class="filter-label">启用</label>
        <select class="input" v-model.number="filters.enableStatus" @change="reload">
          <option :value="-1">全部</option>
          <option :value="1">启用</option>
          <option :value="0">禁用</option>
        </select>

        <label class="filter-label">激活</label>
        <select class="input" v-model.number="filters.activationStatus" @change="reload">
          <option :value="-1">全部</option>
          <option :value="1">已激活</option>
          <option :value="0">未激活</option>
        </select>

        <button class="btn secondary" @click="resetFilters">重置</button>
      </div>
    </div>

    <div class="table-container">
      <table class="table">
        <thead>
          <tr>
            <th>协议编号</th>
            <th>协议名称</th>
            <th>启用</th>
            <th>激活</th>
            <th>分账周期</th>
            <th>开始时间</th>
            <th>结束时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="8" class="loading-state">加载中...</td>
          </tr>
          <tr v-else-if="agreements.length === 0">
            <td colspan="8" class="empty-state">暂无数据</td>
          </tr>
          <tr v-else v-for="a in agreements" :key="a.id" class="table-row">
            <td>{{ a.agreementCode || '-' }}</td>
            <td>{{ a.agreementName || '-' }}</td>
            <td>
              <span class="badge" :class="enableBadge(a.enableStatus)">{{ enableText(a.enableStatus) }}</span>
            </td>
            <td>
              <span class="badge" :class="activationBadge(a.activationStatus)">{{ activationText(a.activationStatus) }}</span>
            </td>
            <td>{{ a.dividedCycle ?? '-' }}</td>
            <td>{{ formatDate(a.startTime) }}</td>
            <td>{{ formatDate(a.endTime) }}</td>
            <td>
              <router-link class="btn small" :to="`/divided/agreements/detail/${a.id}`">详情</router-link>
              <button class="btn danger small" @click="onDelete(a.id)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="pagination">
        <div>
          共 {{ pagination.total }} 条记录，第 {{ pagination.current }} / {{ Math.ceil(pagination.total / pagination.pageSize) || 1 }} 页
        </div>
        <div class="pagination-controls">
          <button class="btn secondary sm" :disabled="pagination.current <= 1" @click="changePage(pagination.current - 1)">上一页</button>
          <button class="btn secondary sm" :disabled="pagination.current >= Math.ceil(pagination.total / pagination.pageSize)" @click="changePage(pagination.current + 1)">下一页</button>
        </div>
      </div>
    </div>

    <!-- 新增协议弹窗 -->
    <div v-if="showAddModal" class="modal-overlay" @click.self="closeAddModal">
      <div class="modal">
        <div class="modal-header">
          <h3>新增分账协议</h3>
        </div>
        <div class="modal-body">
          <div class="form-grid">
            <label>协议名称</label>
            <input class="input" v-model="addForm.AgreementName" placeholder="必填" />

            <label>商户ID</label>
            <input class="input" v-model="addForm.MerchantId" placeholder="必填" />

            <label>分账周期</label>
            <input class="input" type="number" v-model.number="addForm.DividedCycle" placeholder="例如：30" />

            <label>开始时间</label>
            <input class="input" type="datetime-local" v-model="addForm.StartTime" />

            <label>结束时间</label>
            <input class="input" type="datetime-local" v-model="addForm.EndTime" />

            <label>父协议ID</label>
            <input class="input" v-model="addForm.ParentAgreementId" placeholder="可选" />
          </div>
          <div v-if="addError" class="error-message">{{ addError }}</div>
        </div>
        <div class="modal-footer">
          <button class="btn secondary" @click="closeAddModal">取消</button>
          <button class="btn primary" :disabled="submitting" @click="submitAdd">{{ submitting ? '提交中...' : '提交' }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { isSuccess } from '../services/types'
import { getDividedAgreementList, addDividedAgreement, deleteDividedAgreement, type DividedAgreementRequest, type DividedAgreementResponse } from '../services/divided'

const router = useRouter()
const loading = ref(false)
const agreements = ref<DividedAgreementResponse[]>([])
const filters = reactive({ key: '', merchantId: '', enableStatus: -1, activationStatus: -1 })
const pagination = reactive({ current: 1, pageSize: 10, total: 0 })

// 新增弹窗
const showAddModal = ref(false)
const submitting = ref(false)
const addError = ref('')
const addForm = reactive<DividedAgreementRequest>({ AgreementName: '', MerchantId: '', DividedCycle: 30, StartTime: '', EndTime: '', ParentAgreementId: '' })

/**
 * 文件级注释：
 * 分账协议管理页面，实现搜索、分页、列表展示及基本新增/删除操作。
 * 前端调用接口以返回值的 code === 0 判定为成功。
 */

/**
 * 函数级注释：加载分账协议列表
 * @returns void 无返回值，内部更新 agreements 与 pagination
 * @throws 可能抛出网络异常，已在内部 try-catch 处理
 */
async function loadAgreements() {
  loading.value = true
  try {
    const res = await getDividedAgreementList(
      pagination.current,
      pagination.pageSize,
      filters.key,
      filters.merchantId,
      filters.enableStatus,
      filters.activationStatus
    )
    if (isSuccess(res)) {
      agreements.value = (res.data?.items || []) as DividedAgreementResponse[]
      pagination.total = res.data?.total || agreements.value.length
    } else {
      agreements.value = []
      pagination.total = 0
      console.warn('获取分账协议失败:', res?.message)
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    loading.value = false
  }
}

/**
 * 函数级注释：打开新增弹窗
 * @returns void
 */
function openAddModal() { showAddModal.value = true }

/**
 * 函数级注释：关闭新增弹窗并重置表单
 * @returns void
 */
function closeAddModal() {
  showAddModal.value = false
  addForm.AgreementName = ''
  addForm.MerchantId = ''
  addForm.DividedCycle = 30
  addForm.StartTime = ''
  addForm.EndTime = ''
  addForm.ParentAgreementId = ''
  addError.value = ''
}

/**
 * 函数级注释：提交新增协议
 * @returns void
 * @throws 可能抛出网络异常，内部处理后显示错误文案
 */
async function submitAdd() {
  if (!addForm.AgreementName || !addForm.MerchantId) {
    addError.value = '协议名称与商户ID为必填项'
    return
  }
  submitting.value = true
  addError.value = ''
  try {
    const res = await addDividedAgreement(addForm)
    if (isSuccess(res)) {
      closeAddModal()
      await loadAgreements()
    } else {
      addError.value = res?.message || '新增失败'
    }
  } catch (e: any) {
    addError.value = e?.message || '网络异常'
  } finally {
    submitting.value = false
  }
}

/**
 * 函数级注释：删除协议
 * @param id 协议ID
 * @returns void
 */
async function onDelete(id?: string) {
  if (!id) return
  try {
    const res = await deleteDividedAgreement({ Id: id })
    if (isSuccess(res)) {
      await loadAgreements()
    } else {
      console.warn('删除失败:', res?.message)
    }
  } catch (e) {
    console.error('删除异常:', e)
  }
}

/**
 * 函数级注释：格式化时间
 * @param v 时间字符串
 * @returns 中文本地时间或 '-'
 */
function formatDate(v?: string) {
  if (!v) return '-'
  try { return new Date(v).toLocaleString('zh-CN') } catch { return v }
}

/**
 * 函数级注释：启用状态文案
 * @param s 启用状态
 * @returns 文案
 */
function enableText(s?: number) {
  if (s === 1) return '启用'
  if (s === 0) return '禁用'
  return '未知'
}

/**
 * 函数级注释：启用状态徽标样式
 * @param s 启用状态
 * @returns 样式类名
 */
function enableBadge(s?: number) {
  if (s === 1) return 'badge active'
  if (s === 0) return 'badge inactive'
  return 'badge'
}

/**
 * 函数级注释：激活状态文案
 * @param s 激活状态
 * @returns 文案
 */
function activationText(s?: number) {
  if (s === 1) return '已激活'
  if (s === 0) return '未激活'
  return '未知'
}

/**
 * 函数级注释：激活状态徽标样式
 * @param s 激活状态
 * @returns 样式类名
 */
function activationBadge(s?: number) {
  if (s === 1) return 'badge active'
  if (s === 0) return 'badge inactive'
  return 'badge'
}

/**
 * 函数级注释：重置筛选并重新加载
 * @returns void
 */
function resetFilters() {
  filters.key = ''
  filters.merchantId = ''
  filters.enableStatus = -1
  filters.activationStatus = -1
  pagination.current = 1
  loadAgreements()
}

/**
 * 函数级注释：切换页码
 * @param p 目标页码
 * @returns void
 */
function changePage(p: number) {
  pagination.current = p
  loadAgreements()
}

/**
 * 函数级注释：防抖函数
 * @param fn 需要防抖的函数
 * @param delay 延迟毫秒
 * @returns 包装后的函数
 */
function debounce<T extends (...args: any[]) => void>(fn: T, delay = 300) {
  let t: any
  return (...args: any[]) => {
    clearTimeout(t)
    t = setTimeout(() => fn(...args), delay)
  }
}

const onKeyChange = debounce(() => {
  pagination.current = 1
  loadAgreements()
}, 300)

/**
 * 函数级注释：重新加载列表
 * @returns void
 */
function reload() { pagination.current = 1; loadAgreements() }

onMounted(loadAgreements)
</script>

<style scoped>
.header { display: flex; align-items: center; justify-content: space-between; }
.filters { padding: var(--space-4); }
.filter-row { display:flex; align-items:center; gap: var(--space-3); flex-wrap: wrap; }
.filter-label { color: var(--text-secondary); }
.flex-1 { flex: 1; min-width: 240px; }
.table { width: 100%; border-collapse: collapse; }
.table th, .table td { padding: 12px; border-bottom: 1px solid var(--border); }
.badge { padding: 2px 8px; border-radius: var(--radius); font-size: var(--text-sm); }
.badge.active { background: var(--primary-50); color: var(--primary-700); }
.badge.inactive { background: var(--bg-secondary); color: var(--text-secondary); }
.table-row:hover { background: var(--bg-secondary); }
.loading-state, .empty-state { text-align: center; padding: var(--space-6); color: var(--text-secondary); }
.pagination { display: flex; align-items: center; justify-content: space-between; padding: var(--space-4); }
.pagination-controls { display:flex; gap: var(--space-2); }
.table-container { overflow-x: auto; }

/* 简易模态框样式 */
.modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.3); display:flex; align-items: center; justify-content: center; }
.modal { width: 600px; max-width: 90vw; background: var(--card-bg); border: 1px solid var(--border); border-radius: var(--radius-lg); box-shadow: var(--shadow-lg); }
.modal-header { padding: var(--space-4); border-bottom: 1px solid var(--border); }
.modal-body { padding: var(--space-4); }
.modal-footer { padding: var(--space-4); display:flex; justify-content: flex-end; gap: var(--space-2); border-top: 1px solid var(--border); }
.form-grid { display:grid; grid-template-columns: 120px 1fr; gap: var(--space-3); align-items: center; }
.error-message { color: var(--danger); padding: var(--space-2) 0; }

@media (max-width: 768px) {
  .form-grid { grid-template-columns: 1fr; }
}
</style>

